from __future__ import absolute_import, unicode_literals
from celery import shared_task
from Dashboard.models import DailySubmitInfo
from PeopleInfo.models import *
from django.template.loader import get_template
import os
from django.conf import settings
from Dashboard.functions import *
from DataManagement.utils import MyResponse
from dateutil.relativedelta import relativedelta
import datetime
from time import time
import requests
import json

def helper(data):
    arr1, arr2 = [], []
    for col1, col2 in data:
        arr1.append(col1)
        arr2.append(col2)
    return arr1, arr2


# 定义一个计算执行时间的函数作装饰器，传入参数为装饰的函数或方法
def print_execute_time(func):
    from time import time

    # 定义嵌套函数，用来打印出装饰的函数的执行时间
    def wrapper(*args, **kwargs):
        # 定义开始时间和结束时间，将func夹在中间执行，取得其返回值
        start = time()
        func_return = func(*args, **kwargs)
        end = time()
        # 打印方法名称和其执行时间
        print(f'{func.__name__}() execute time: {end - start}s')
        # 返回func的返回值
        return func_return

    # 返回嵌套的函数
    return wrapper


@shared_task
def generate_illness_report():
    start_time = time()
    title = '东莞理工学院防疫网报系统数据分析报告'
    unhealthy, fever, caugh, shortness_of_breath, other = fun6()

    avg_report_rate = fun8()
    ill_area_teaCount, ill_area_stuCount = ill_count()
    plan_back_dg_count, plan_back_dg_count_beforet, plan_back_dg_count_aftert = sql_execute_fetchone(
        sqlList.get_plan_back_dg_cal)
    at_dg_count, not_at_dg_count = sql_execute_fetchone(sqlList.get_sql_at_dg_count)
    first_time_back_dg, last_time_back_dg = back_dg_first_last()

    # 返莞出行方式，人数
    sql_18_1, sql_18_2 = helper(sql_execute_fetchall(sqlList.SQL_PLAN_BACK_DG_TRANSPORT))
    # 返莞时间 人数
    arr_null = ["-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-"]
    sql_19_1, sql_19_2 = helper(sql_execute_fetchall(sqlList.get_future_back_dongguan_people_num_statistics))
    sql_19_3, sql_19_4 = helper(sql_execute_fetchall(sqlList.get_past_back_dongguan_people_num_statistics))
    sql_19 = sql_19_3
    sql_19.extend(sql_19_1)
    sql_19_4.extend(arr_null)
    arr_null.extend(sql_19_2)

    peoples = sql_execute_fetchall(sqlList.SQL_GET_PEOPLE_INFO)
    people1 = peoples[0][0]
    people2 = peoples[1][0]
    people3 = peoples[2][0]
    people4 = peoples[3][0]
    people5 = peoples[4][0]

    # 全国师生分布地图数据
    china, province = func16()

    # 疫苗健康码信息
    green_tea, yellow_tea, red_tea = healthy_status_total_tea()
    green_stu, yellow_stu, red_stu = healthy_status_total_stu()
    in_controllerd_area1_tea, in_controllerd_area2_tea = healthy_controller_area_total_tea()
    in_controllerd_area1_stu, in_controllerd_area2_stu = healthy_controller_area_total_stu()
    ym_two_tea, ym_one_tea, ym_no_normal_tea, ym_no_error_tea = healthy_vaccination_total_tea()
    ym_two_stu, ym_one_stu, ym_no_normal_stu, ym_no_error_stu = healthy_vaccination_total_stu()


    # 新增 进校离校人员统计
    today = datetime.date.today().strftime('%Y%m%d')
    inSchool = requests.get("http://yqfk.dgut.edu.cn/auth/ibps/getTodayInSchool?day=" + today).text
    outSchool = requests.get("http://yqfk.dgut.edu.cn/auth/ibps/getTodayOutSchool?day=" + today).text

    today = datetime.date.today().strftime('%Y-%m-%d')
    out_collection = requests.get("http://172.31.200.38:17750/api/studentStatisticsDao?date=" + today)
    code = json.loads(out_collection.text).get('code')
    ## 增加status判断，必须为200才处理。不知道为何校务的异常未报400，后续排查校务接口。叶耀文-2021-09-25记录
    status = json.loads(out_collection.text).get('status')
    if(code!=400 and code!=500 and status==200):
        res_1 = json.loads(out_collection.text).get('data').get('dataResult').get('res_1')
        res_2 = json.loads(out_collection.text).get('data').get('dataResult').get('res_2')
        res_3 = json.loads(out_collection.text).get('data').get('dataResult').get('res_3')
        broken = json.loads(out_collection.text).get('data').get('dataResult').get('broken')
    else:
        res_1 = 0
        res_2 = 0
        res_3 = 0
        broken = 0

    context = {
        'title': title,
        'avg_report_rate': avg_report_rate,
        'reporting_rate_in_recent_5_days': sql_execute_fetchall(sqlList.REPORTING_RATE_IN_RECENT_5_DAYS),
        'physical_condition_of_teachers_and_students_in_recent_5_days': sql_execute_fetchall(
            sqlList.PHYSICAL_CONDITION_OF_TEACHERS_AND_STUDENTS_IN_RECENT_5_DAYS),
        'unhealth': unhealthy,
        'fever': fever,
        'caugh': caugh,
        'shortness_of_breath': shortness_of_breath,
        'other': other,
        # 'sql_7': func7(),
        'sql_8': sql_execute_fetchall(sqlList.get_sql_8),  # 昨日新增身体不适统计
        'sql_10': fun10(),  # 疫情重点关注地区师生分布
        'foreign_count': sql_execute_fetchall(sqlList.SQL_STU_TEA_IN_FOREIGN_ILL),  # 境外疫情重点关注地区师生分布
        # 'sql_11': sql_execute_fetchall(sqlList.SQL_11),  # 今日流入疫情重点关注地区人员名单
        'sql_11_tea': sql_execute_fetchall(sqlList.SQL_11_TEA),  # 今日流入疫情重点关注地区人员教职工名单
        'sql_11_stu': sql_execute_fetchall(sqlList.SQL_11_STU),  # 今日流入疫情重点关注地区人员学生名单
        # 'sql_12': sql_execute_fetchone(SQL_12)[0],
        # 'sql_13': sql_execute_fetchone(SQL_13)[0],
        # 'sql_14': sql_execute_fetchone(SQL_14)[0],
        "top_cities": top_cities(),
        'ill_area_teaCount': ill_area_teaCount,
        'ill_area_stuCount': ill_area_stuCount,
        'back_dg_cal': back_dg_cal(),
        'back_dg_day_cal': sql_execute_fetchall(sqlList.SQL_PLAN_BACK_DG_DAY),
        'back_dg_transport_cal': sql_execute_fetchall(sqlList.SQL_PLAN_BACK_DG_TRANSPORT),
        # 'func15': func15(),
        'func15_stu': func15_stu(),
        'func15_tea': func15_tea(),
        'plan_back_dg_count': plan_back_dg_count,
        'plan_back_dg_count_beforet': plan_back_dg_count_beforet,
        'plan_back_dg_count_aftert': plan_back_dg_count_aftert,
        'at_dg_count': at_dg_count,
        'not_at_dg_count': not_at_dg_count,
        'first_time_back_dg': first_time_back_dg,
        'last_time_back_dg': last_time_back_dg,
        'back_dg_cal_topt': back_dg_cal_topt(),
        'sql_16': sql_execute_fetchall(sqlList.SQL_16),
        'sql_17': sql_execute_fetchall(sqlList.SQL_17),
        'sql_17_tea': sql_execute_fetchall(sqlList.SQL_17_TEA),
        'sql_17_stu': sql_execute_fetchall(sqlList.SQL_17_STU),
        'sql_18_1': sql_18_1,
        'sql_18_2': sql_18_2,
        'sql_19': sql_19,
        'sql_19_1': sql_19_1,
        'sql_19_2': sql_19_2,
        'sql_19_3': sql_19_3,
        'sql_19_4': sql_19_4,
        'arr_null': arr_null,
        'china': china,
        'province': province,
        'second_nocount': sql_execute_fetchall(sqlList.get_second_nocount),
        'people1': people1,
        'people2': people2,
        'people3': people3,
        'people4': people4,
        'people5': people5,
        'out_guangdong': sql_execute_fetchall(sqlList.get_out_guangdong),
        'out_dongguan': sql_execute_fetchall(sqlList.get_out_dongguan),
        'importment_area': sql_execute_fetchall(sqlList.sql_importment_area),
        'importment_area_count': sql_execute_fetchone(sqlList.sql_importment_area_count)[0],
        'next_month': (datetime.datetime.now() + relativedelta(months=+1)).month,
        'abnormal_body_temperature_student': sql_execute_fetchall(sqlList.abnormal_body_temperature_student),
        'continuous_abnormal_body_temperature_student': sql_execute_fetchall(
            sqlList.continuous_abnormal_body_temperature_student),
        'healthy_status_detail_tea': sql_execute_fetchall(sqlList.healthy_status_detail_tea),
        'healthy_status_detail_stu': sql_execute_fetchall(sqlList.healthy_status_detail_stu),

        # 健康码
        'green_tea':green_tea,
        'yellow_tea':yellow_tea,
        'red_tea':red_tea,
        'green_stu':green_stu,
        'yellow_stu':yellow_stu,
        'red_stu':red_stu,
        'in_controllerd_area1_tea':in_controllerd_area1_tea,
        'in_controllerd_area2_tea':in_controllerd_area2_tea,
        'in_controllerd_area1_stu':in_controllerd_area1_stu,
        'in_controllerd_area2_stu':in_controllerd_area2_stu,
        'ym_two_tea':ym_two_tea,
        'ym_one_tea':ym_one_tea,
        'ym_no_normal_tea':ym_no_normal_tea,
        'ym_no_error_tea':ym_no_error_tea,
        'ym_two_stu':ym_two_stu,
        'ym_one_stu':ym_one_stu,
        'ym_no_normal_stu':ym_no_normal_stu,
        'ym_no_error_stu':ym_no_error_stu,



        # 学生进校离校统计
        'inSchool' : inSchool,
        'outSchool' : outSchool,
        'res_1': res_1,
        'res_2': res_2,
        'res_3': res_3,
        'broken': broken,
        # 'path': os.path.join(settings.BASE_DIR, 'templates/report.html'),

        # 请将以下两个变量放至末尾
        'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
        'time_consuming': time() - start_time
    }

    template = get_template('Dashboard/report.html')
    html = template.render(context)

    def save_file(html, filepath):
        file = open(filepath, 'w', encoding='utf-8')
        file.write(html)
        file.close()

    # 存档
    filename1 = os.path.join(settings.STATIC_ROOT,
                             'report/{}.html'.format(datetime.datetime.now().strftime('%Y-%m-%d')))
    # 分享
    filename2 = os.path.join(settings.STATIC_ROOT, 'report.html')
    # 模板
    filename3 = os.path.join(settings.BASE_DIR, 'templates/report.html')


    save_file(html, filename1)
    save_file(html, filename2)
    save_file(html, filename3)

    return html


@shared_task
def teacher_access_check_update(username):
    item = EntranceGuardList.objects.filter(username=username).first()
    if not item:
        return {
            'data': None,
            'message': '白名单无该用户',
            'code': AccessCheck.WITHOUT_USER
        }

    # 不再启用该判断 2021-12-20 ，相关逻辑由新疫情系统负责
    #daily_report = DailySubmitInfo.objects.filter(username=username).order_by('-submit_time').first()
    #if daily_report:
    #    if not item.lock:
    #        if item.status == 1:
                # 尝试移除
    #            item.try_remove(daily_report)
            # elif item.status == 2:
                # 尝试加入
                # item.try_add(daily_report)
    #    else:
    #        item.save()

    code = AccessCheck.ACCESS if item.status == 1 else AccessCheck.NOT_ALLOWED
    data = {
        'username': item.username,
        'nickname': item.nickname,
        'level': item.level,
        'reason': item.reason,
        'code': code
    }

    res = {
        'data': data,
        'message': item.reason,
        'code': code
    }
    return res


